#include "StdAfx.h"


namespace Database
{
	namespace _xxImpl_MySql
	{
		MysqlDatabase::MysqlDatabase()
		{
			m_pMySql = mysql_init(NULL);
		}

		bool MysqlDatabase::Connect(std::string szHost, std::string szUser, std::string szPass, std::string szDb, uint32 port)
		{
			MYSQL* pMysql = mysql_real_connect(m_pMySql, szHost.c_str(), szUser.c_str(), szPass.c_str(), szDb.c_str(), port, NULL, 0);
			return pMysql != NULL;
		}

		std::string MysqlDatabase::EscapeString(std::string szFrom)
		{
			char pTo[512];
			uint64 size = mysql_real_escape_string(m_pMySql, pTo, szFrom.c_str(), szFrom.length());
			std::string szEscapedString(pTo);
			return szEscapedString;
		}

		void MysqlDatabase::Close()
		{
			mysql_close(m_pMySql);
		}

		std::string MysqlDatabase::GetLastError()
		{
			const char* err = mysql_error(m_pMySql);
			if(err == NULL)
				return "No error occured!";
			if(*err == 0)
				return "No error occured!";

			return std::string(err);
		}

		bool MysqlDatabase::Execute(std::string szQuery)
		{
			return !(mysql_real_query(m_pMySql, szQuery.c_str(), szQuery.length()));
		}

		IQueryResult* MysqlDatabase::Query(std::string szQuery, ...)
		{
			char sql[1024];
			va_list vlist;
			va_start(vlist, szQuery);
			vsnprintf_s(sql, 1024, szQuery.c_str(), vlist);
			va_end(vlist);

			szQuery = std::string(sql);

			uint32 res = mysql_real_query(m_pMySql, szQuery.c_str(), szQuery.length());
			if(res)
				return 0;

			MYSQL_RES* pRes = mysql_store_result(m_pMySql);

			if(mysql_num_rows(pRes) == 0)
				return 0;

			IQueryResult* pRRes = new QueryResult(pRes);

			return pRRes;
		}
	}
}
